<?php
include 'model/Cartoon.php';
/**
 * 接收用户消息并进行回复
 */
class Respose {

	//存储接收到的xml数据对象
	private $XML_receive;
	//准备回复用的文本XML
	private $XML_text = '<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[text]]></MsgType>
							<Content><![CDATA[%s]]></Content>
						</xml>';
	private $accessToken;

//======================初始操作=============================
	//构造方法
	public function __construct()
	{
		//获取AccessToken
		$this -> accessToken = GetAccessToken::getToken();
		// $this -> defineMenu();
	}
	//自定义菜单
	public function defineMenu()
	{
		$url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $this -> accessToken;
		$postStr = [
						'button' => [
							[
								'type'=>'click',
							 	'name'=>urlencode('最新资源'),
							 	'key'=>'111'
							 ],
							[
								'name'=>urlencode('菜单'),
							 	'sub_button'=>[
							 			['type'=>'click',
							 			'name'=>urlencode('哈哈'),
							 			'key'=>'111'],
							 			['type'=>'click',
							 			'name'=>urlencode('呵呵'),
							 			'key'=>'111']
							 		]
							 ]
						]
		];
		$postStr = urldecode(json_encode($postStr));
		$result = $this -> httpCurl($url,'post','json',$postStr);
		// var_dump($result);
	}
//======================接收信息=============================
	//被动回复消息
	public function responseMsg() 
	{
		//获取XML数据
		if (PHP_VERSION >= 7) {
			// PHP7.0以上版本使用此方式获取数据
			$postStr = file_get_contents('php://input');
		} else {
			//PHP7.0以下版本使用此方式获取数据
			$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		}
		//将XML数据解析为对象
		$this -> XML_receive = simplexml_load_string($postStr);
		//获得接收消息的类型
		$handle = 'receive' . ucfirst($this -> XML_receive -> MsgType);
		//依据消息进行回复
		$this -> $handle();
	}

//======================依据消息类型分流=============================
	//接收text时的回复
	private function receiveText()
	{
		//获得回复内容
		$content = $this -> XML_receive -> Content;
		//如果开头为 动漫：则调用搜索方法
		if (mb_substr($content,0,3) == '动漫：') {
			$this -> cartoonSearch(mb_substr($content,3));
		}
		
	}
	//发生事件时的回复
	private function receiveEvent()
	{
		//事件列表
		$type = [
					'subscribe' => '欢迎欢迎，谢天谢地终于等到你！想要动漫资源的童鞋可以回复“动漫：”加上心仪的动漫名字进行搜索哦！如 ‘动漫：政宗君的复仇’。'
			];
		//获得当前事件类型
		$event = $this -> XML_receive -> Event;
		$event = (string)$event;
		if (array_key_exists($event, $type)) {
			//回复文本
			$this -> responseText($type[$event]);
		}
	}

//======================依据消息内容再分流=============================
	//回复动漫搜索结果
	private function cartoonSearch($content)
	{
		$cartoonModel = new Cartoon('cartoon');
		$result = $cartoonModel -> cartoonSearch($content);
		//如果查询到数据 就回复图文
		if ($result) {
			if (count($result) > 1) {
				foreach ($result as $key => $value) {
					$result[$key][0] = $value[0] . '  神秘代码:' . $value[1];
				}
			}
			$this -> responseNews($result);
			exit;
		}
		//如果没查询到 回复文本
		$this -> responseText('阿欧，搜不到哎。。请不要输入错别字或无关的字符哦[表情]');
	}

//======================基础操作=============================
	//回复文本
	private function responseText($content)
	{
		$XML_text = sprintf($this -> XML_text,$this -> XML_receive->FromUserName,$this -> XML_receive ->ToUserName,time(),$content);
		echo $XML_text;
	}
	//回复图文
	private function responseNews($data)
	{
		$XML_news = '<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[news]]></MsgType>
					<ArticleCount>' . count($data) . '</ArticleCount>
					<Articles>';
		foreach ($data as $key => $value) {
		$XML_news .='<item>
					<Title><![CDATA['.$value[0].']]></Title> 
					<Description><![CDATA[ 提取码：'.$value[1].']]></Description>
					<PicUrl><![CDATA['.$value[2].']]></PicUrl>
					<Url><![CDATA['.$value[3].']]></Url>
					</item>';
		}			
		$XML_news .='</Articles>
					</xml>';
		$XML_news = sprintf($XML_news,$this -> XML_receive->FromUserName,$this -> XML_receive->ToUserName,time());

		echo $XML_news;
	}
	//回复图片
	private function responseImg($content)
	{
		$XML_text = sprintf($this -> XML_text,$this -> XML_receive->FromUserName,$this -> XML_receive ->ToUserName,time(),$content);
		echo $XML_text;
	}
	//curl请求
	private function httpCurl($url,$type='get',$res='json',$arr='')
	{
		//初始化
		$ch = curl_init();
		//设置参数
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		if ($type == 'post') {
			curl_setopt($ch, CURLOPT_POST,1);
			curl_setopt($ch, CURLOPT_POSTFIELDS,$arr);
		}
		//执行
		$result = curl_exec($ch);
		if ($res == 'json') {
			if (curl_errno($ch)) {
				return curl_error($ch);
			} else {
				return json_decode($result,true);
			}
		}
		//关闭
		curl_close($ch);
	}
//======================魔术方法=============================
	//
	public function __call($name,$arguement)
	{
		$content = '对不起，该功能尚未开放。您可以尝试回复 “动漫：”加上动漫名称来搜索站内的资源哦！';
		$XML_text = sprintf($this -> XML_text,$this -> XML_receive->FromUserName,$this -> XML_receive->ToUserName,time(),$content);

		echo $XML_text;
	}
}